from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
from dotenv import load_dotenv
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 加载环境变量
load_dotenv()

# 使用 SQLite 数据库
SQLALCHEMY_DATABASE_URL = "sqlite:///./dormitory.db"

try:
    logger.info("正在连接数据库：SQLite")
    engine = create_engine(
        SQLALCHEMY_DATABASE_URL,
        connect_args={"check_same_thread": False},
        echo=True  # 启用SQL语句日志
    )
    logger.info("数据库连接成功")
except Exception as e:
    logger.error(f"数据库连接失败：{str(e)}")
    raise

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

# 数据库依赖项
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# 创建所有表
def init_db():
    try:
        logger.info("正在创建数据库表...")
        from app.models.models import Base
        Base.metadata.create_all(bind=engine)
        logger.info("数据库表创建成功")
    except Exception as e:
        logger.error(f"创建数据库表时出错：{str(e)}")
        raise 